package elitech.vietnam.myfashion.view;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParserException;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshGridView2;
import com.huewu.pla.lib.MultiColumnListView;
import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;

import elitech.vietnam.myfashion.MainActivity;
import elitech.vietnam.myfashion.R;
import elitech.vietnam.myfashion.config.Const;
import elitech.vietnam.myfashion.dialog.NewPostDialog;
import elitech.vietnam.myfashion.dialog.UserInfoDialog;
import elitech.vietnam.myfashion.doinbackground.CallServiceTask;
import elitech.vietnam.myfashion.entites.Post;
import elitech.vietnam.myfashion.extend.GridStylerArrayAdapter;

public class MyStyleView extends LinearLayout implements
		OnRefreshListener2<MultiColumnListView>, View.OnClickListener {

	private static final int NUM_ITEMS = 10;
	public static final int LOGINACTIVITY = 1;

	private MainActivity mContext;
	private PullToRefreshGridView2 mPullRefreshGridView;
	private GridStylerArrayAdapter mAdapter;
	private ImageView mAvatar;
	private TextView mUserName, mProfile, mTxtTitle;
	private ImageView mBtnNewPost;
	public static MyStyleView mInstance = null;
	private int countItems = 0;
	private View mMainMenu;

	public MyStyleView(MainActivity context) {
		super(context);
		this.mContext = context;
		mInstance = this;

		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		if (inflater != null) {
			inflater.inflate(R.layout.mystyle, this);
		}
		this.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT));

		mPullRefreshGridView = (PullToRefreshGridView2) this
				.findViewById(R.id.mystyler_gridview);
		mAvatar = (ImageView) this.findViewById(R.id.mystyle_imgAvatar);
		mUserName = (TextView) this.findViewById(R.id.mystyle_txtUsername);
		mProfile = (TextView) this.findViewById(R.id.mystyle_txtProfile);
		mBtnNewPost = (ImageView) this.findViewById(R.id.mystyle_imgNewPost);
		mMainMenu = (LinearLayout) findViewById(R.id.main_menu);
		mTxtTitle = (TextView) findViewById(R.id.main_title);
		mMainMenu.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mContext.callMenu();
			}
		});
		mTxtTitle.setText(R.string.mystyle);
		mPullRefreshGridView.setMode(Mode.PULL_FROM_END);
		mPullRefreshGridView.setOnRefreshListener(this);
		mBtnNewPost.setOnClickListener(this);
		mAvatar.setOnClickListener(this);

		mAdapter = new GridStylerArrayAdapter(mContext, R.id.mystyler_gridview,
				0, mContext.mListMyStyles);
		mPullRefreshGridView.setPadding(0, 1, 1, 0);
		mPullRefreshGridView.setAdapter(mAdapter);

		if (mContext.mUser != null)
			LoadMemberInfo();

		if (mContext.mListMyStyles.size() == 0)
			RefreshMyStyle();

	}
	
	public void onActivityResult(String imagePath) {
		new NewPostDialog(mContext, imagePath, true) {
			public void onUploadDone() {
				mContext.mListMyStyles.clear();
				GetMyStyle();
			};
		}.show();
	}

	public void LoadMemberInfo() {
		UrlImageViewHelper.setUrlDrawable(mAvatar, Const.SERVER_IMAGE_THUMB_URL
				+ mContext.mUser.Image, R.drawable.no_avatar);
		mUserName
				.setText((mContext.mUser.NickName.equals("")) ? mContext.mUser.Name
						: mContext.mUser.NickName);
		mProfile.setText(mContext.mUser.Profile);
		mContext.mEditedInfo = false;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.mystyle_imgNewPost:
			new Dialog(mContext).show();
			break;
//		case R.id.mystyle_imgEdit:
//			mContext.mMainPageView.mViewPager.setCurrentItem(5, false);
//			mContext.changeTitle(mContext.getString(R.string.setting), false);
//			if (mContext.mUser == null) {
//				Intent i = new Intent(mContext, LoginActivity.class);
//				mContext.startActivityForResult(i, LOGINACTIVITY);
//				break;
//			} else {
//				Fragment fragment = new Fragment() {
//					@Override
//					public View onCreateView(LayoutInflater inflater,
//							ViewGroup container, Bundle savedInstanceState) {
//						return new EditProfileView(mContext);
//					}
//
//					@Override
//					public void onDestroy() {
//						File file = new File(MainActivity.IMAGE_TEMP);
//						if (file.exists())
//							file.delete();
//						super.onDestroy();
//					}
//				};
//				mContext.replaceFragment(fragment, true);
//			}
//			break;
		case R.id.mystyle_imgAvatar:
			if (mContext.mUser != null)
				new UserInfoDialog(mContext, mContext.mUser).show();
			break;
		}
	}

	public void onResume() {
		if (mPullRefreshGridView.isRefreshing())
			mPullRefreshGridView.onRefreshComplete();
	}

	public void GetMyStyle() {
		new CallServiceTask() {
			private ArrayList<Post> rs = new ArrayList<Post>();

			public void work() {
				try {
					if (mContext.mUser != null)
						rs = service.getMyStyle(mContext.mUser.Id,
								mContext.mListMyStyles.size(), NUM_ITEMS);
				} catch (NullPointerException e) {
				} catch (IOException e) {
				} catch (XmlPullParserException e) {
				}
			};

			protected void onPostExecute(Void result) {
				if (rs != null) {
					mContext.mListMyStyles.addAll(rs);
					countItems = countItems + rs.size();
				}
				mAdapter.notifyDataSetChanged();
				mPullRefreshGridView.onRefreshComplete();
			};
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	public void RefreshMyStyle() {
		new CallServiceTask() {
			private ArrayList<Post> rs = new ArrayList<Post>();

			public void work() {
				try {
					if (mContext.mUser != null){
						int numb = (countItems>NUM_ITEMS)? countItems:NUM_ITEMS;
						rs = service
								.getMyStyle(mContext.mUser.Id, 0, numb);
					}
				} catch (NullPointerException e) {
				} catch (IOException e) {
				} catch (XmlPullParserException e) {
				}
			};

			protected void onPostExecute(Void result) {
				if (rs != null) {
					mContext.mListMyStyles.clear();
					mContext.mListMyStyles.addAll(rs);
					countItems = rs.size();
				}
				mAdapter.notifyDataSetChanged();
				mPullRefreshGridView.onRefreshComplete();
			};
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	private class Dialog extends android.app.Dialog implements
			View.OnClickListener {

		public Dialog(Context context) {
			super(context, R.style.Dialog);
		}

		@Override
		protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.dl_cam);

			this.findViewById(R.id.dl_cam_cam).setOnClickListener(this);
			this.findViewById(R.id.dl_cam_lib).setOnClickListener(this);
		}

		@Override
		public void onClick(View v) {
			Intent intent = null;
			int request = 0;
			switch (v.getId()) {
			case R.id.dl_cam_cam:
				intent = new Intent(
						android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
						Uri.fromFile(new File(MainActivity.IMAGE_TEMP)));
				request = MainActivity.CAMERA_MYSTYLE;
				break;

			case R.id.dl_cam_lib:
				intent = new Intent(Intent.ACTION_PICK,
						MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				request = MainActivity.LIBRAR_MYSTYLE;
				break;
			}
			if (intent != null)
				mContext.startActivityForResult(intent, request);
			this.dismiss();
		}
	}

	@Override
	public void onPullDownToRefresh(
			PullToRefreshBase<MultiColumnListView> refreshView) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPullUpToRefresh(
			PullToRefreshBase<MultiColumnListView> refreshView) {
		GetMyStyle();
	}

}
